# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         ext_mysql.py
# Description:
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2021/4/25 13:21
# -------------------------------------------------------------------------------
import json

from apps.HttpAutoTestService.models import Parameter
from utils.mysql_client import MysqlClient

__all__ = ['MysqlDB']


class MysqlDB(object):

    def __init__(self, mysql_tag, db=None):
        """
        初始化
        Args:
            mysql_tag:mysql数据库标识
            db:数据库
        """
        self.mysql_tag = mysql_tag
        self.db = db
        self.mysql_conf = {}
        parameter = Parameter.objects.filter(key='MYSQL_CONFIG', is_deleted=False).first()
        if parameter and parameter.value:
            data = json.loads(parameter.value)
            self.mysql_conf = self.parse_db_conf(data=data)
        self.mysql_client = MysqlClient(**self.mysql_conf)
        self.conn = self.mysql_client.get_conn()

    def parse_db_conf(self, data):
        """
        解析数据库配置信息
        Args:
            data:

        Returns:

        """
        if isinstance(data, dict):
            if self.mysql_tag == data.get('mysql_tag'):
                return {
                    'host': data.get('host', None),
                    'port': data.get('port', 3306),
                    'user': data.get('user', None),
                    'password': data.get('password', None),
                    'db': self.db or data.get('db', None),
                    'charset': data.get('charset', 'utf8'),
                    'ssh_host': data.get('ssh_host', None),
                    'ssh_username': data.get('ssh_username', None),
                    'ssh_password': data.get('ssh_password', None),
                    'use_ssh_tunnel': data.get('use_ssh_tunnel', False)
                }
        elif isinstance(data, list):
            res = None
            for item in data:
                res = self.parse_db_conf(item)
                if res is not None:
                    break
            return res

    def query_one(self, sql):
        """
        查询一条数据
        Args:
            sql:

        Returns:字典数据

        """
        result = self.mysql_client.query_one(conn=self.conn, sql=sql)
        self.mysql_client.close_conn(conn=self.conn)
        self.mysql_client.close()
        return result

    def query_many(self, sql):
        """
        查询所有数据
        Args:
            sql:

        Returns:列表数据

        """
        result = self.mysql_client.query_many(conn=self.conn, sql=sql)
        self.mysql_client.close_conn(conn=self.conn)
        self.mysql_client.close()
        return result

    def exec_one(self, sql):
        """
        执行单条 插入、更新、删除sql
        Args:
            sql:

        Returns:

        """
        self.mysql_client.execute_one(conn=self.conn, sql=sql)
        self.mysql_client.close_conn(conn=self.conn)
        self.mysql_client.close()

    def exec_many(self, sql, data_list):
        """
        执行单条 插入、更新、删除sql
        Args:
            sql:
            data_list:插入、更新、删除sql的参数，参数格式为元组列表，示例：[(1,2,3,4),(1,2,3,4)]

        Returns:

        """
        self.mysql_client.execute_many(conn=self.conn, sql=sql, datas=data_list)
        self.mysql_client.close_conn(conn=self.conn)
        self.mysql_client.close()
